﻿import re

import logging
from google.appengine.ext import db
from django.http import HttpResponse, HttpResponseRedirect

class feed(db.Model):
    feed_name = db.TextProperty()


class Entry(db.Model):
    feed_name = db.TextProperty()
    order = db.IntegerProperty()
    author = db.TextProperty()
    title = db.TextProperty()
    url = db.TextProperty()
    content = db.TextProperty()
    create_date = db.DateTimeProperty()
    update_date = db.DateTimeProperty()
    upload_date = db.DateTimeProperty(auto_now_add = True)
    
    def toHTML(self):
        html = ''
        html += '<div class="feed">\n'
        html += '  <div class="title">%d. <a href="%s" target="_blank">%s</a></div>\n'%(self.order, self.url, self.title)
        html += '  <div class="content">%s</div>\n'%(self.content)
        html += '</div>'

        return html


# ##########################################################################################################################
# /rss/
def rss(request):
    feed_name = fs(request.GET.get('name', None))

    html = ''
    if feed_name:
        entries = db.GqlQuery("SELECT * FROM Entry WHERE feed_name=:1 ORDER BY upload_date DESC", feed_name).fetch(100)
        #entries = Entry.all()
        #entries.order('-upload_date')
        
        html = ''

        style='''<style>
            * {font-family: Consolas; font-size: 16px;}
            .feed {margin: 0.8em 1em 0.8em 1em; border: thin solid gray;}
            .title {padding: 0.3em 0 0.3em 1em; background-color:gray; font-weight:bold; font-size: 20px; text-decoration:none;}
            .content {padding: 0 0 0 1em; }\n</style>\n'''

        html += '<html>\n<head>\n<title>%s</title>\n%s\n</head>\n<body>\n'%(feed_name, style)
        
        idx = 1
        #entries = reversed(entries)
        for entry in entries:
            entry.order = idx
            html += entry.toHTML()+"\n\n"
            idx += 1
        html += '</body></html>'

    return HttpResponse(html)



# ##########################################################################################################################
# /rss/add/
def add(request):
    feed_name = fs(request.POST.get('name', None))
    author = fs(request.POST.get('author', ''))
    title = fs(request.POST.get('title', ''))
    url = fs(request.POST.get('url', ''))
    content = fs(request.POST.get('content', ''))
    create_date = request.POST.get('create_date', None)
    update_date = request.POST.get('update_date', None)
    
    if feed_name is None:
        return HttpResponse('error!')
    
    entry = Entry(feed_name=feed_name, author=author, title=title, url=url, content=content, create_date=create_date, update_date=update_date)
    entry.put()
    
    return HttpResponse('success!')
    
def fs(str):
    if str is None:
        return None
    else:
        return unicode(str, 'utf-8', 'ignore')